package javango.forms.fields;

import java.lang.annotation.Annotation;
import java.util.LinkedHashMap;
import java.util.Map;

import com.google.inject.Inject;

import javango.forms.fields.annotations.Choice;
import javango.forms.fields.annotations.ChoiceFieldProperties;
import javango.forms.widgets.SelectMultipleWidget;
import javango.forms.widgets.WidgetFactory;

/**
 * 
 * @author johns
 */

public class MultipleSelectField extends SelectField {

	@Inject
	public MultipleSelectField(WidgetFactory widgetFactory) {
		super(widgetFactory);
		setWidget(SelectMultipleWidget.class);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void handleAnnotation(Annotation annotation) {
		if (annotation instanceof ChoiceFieldProperties) {
			ChoiceFieldProperties props = (ChoiceFieldProperties)annotation;
			if (getChoices() == null) {
				setChoices(new LinkedHashMap<String,String>());
			}
			
			for(Choice c : props.choices()) {
				getChoices().put(c.key(), c.value());
			}			
		}
		super.handleAnnotation(annotation);
	}
	
	@Override
	public Object clean(String[] values, Map errors) {
		String[] clean = new String[values.length];
		int i=0;
		for(String val : values) {
			String stringValue = (String)clean(val, errors);
			if (!getChoices().containsKey(stringValue)) {
				errors.put(this.name, "Select a valid choice. That choice is not one of the available choices.");
			}
			clean[i++] = stringValue; 
		}
		return clean;
	}

}
